/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.netbeans.modules.project.libraries.ui;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JPanel;
import org.netbeans.api.annotations.common.NonNull;
import org.netbeans.api.project.libraries.LibraryManager;
import static org.netbeans.modules.project.libraries.ui.Bundle.*;
import org.netbeans.spi.project.libraries.ArealLibraryProvider;
import org.netbeans.spi.project.libraries.LibraryStorageArea;
import org.netbeans.spi.project.libraries.support.LibrariesSupport;
import org.openide.filesystems.FileUtil;
import org.openide.util.Exceptions;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
import org.openide.util.Utilities;

class AllLibrariesCustomizer extends JPanel implements HelpCtx.Provider {
    
    private org.netbeans.modules.project.libraries.ui.LibrariesCustomizer librariesCustomizer;

    AllLibrariesCustomizer() {
        initComponents();
        librariesCustomizer = new org.netbeans.modules.project.libraries.ui.LibrariesCustomizer(LibraryStorageArea.GLOBAL);
        placeholder.add(librariesCustomizer);
        initModel();
    }

    public boolean apply() {
        return librariesCustomizer.apply();
    }

    @Override public HelpCtx getHelpCtx() {
        return librariesCustomizer.getHelpCtx();
    }
    
    @Messages("LABEL_Global_Libraries=Global Libraries")
    private void initModel() {
        List<String> items = new ArrayList<String>();
        items.add(LABEL_Global_Libraries());
        for (LibraryManager man : LibraryManager.getOpenManagers()) {
            if (man.getLocation() == null) {
                continue;
            }
            items.add(LibrariesSupport.convertURIToFilePath(URI.create(man.getLocation().toExternalForm())));
        }
        libraryManagerComboBox.setModel(new DefaultComboBoxModel(items.toArray(new String[0])));
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        libraryManagerComboBox = new javax.swing.JComboBox();
        placeholder = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();

        libraryManagerComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                libraryManagerComboBoxActionPerformed(evt);
            }
        });

        placeholder.setLayout(new java.awt.BorderLayout());

        jLabel1.setText(org.openide.util.NbBundle.getMessage(AllLibrariesCustomizer.class, "AllLibrariesCustomizer.jLabel1.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(placeholder, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 430, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(libraryManagerComboBox, 0, 289, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(libraryManagerComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(placeholder, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void libraryManagerComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_libraryManagerComboBoxActionPerformed
        int index = libraryManagerComboBox.getSelectedIndex();
        if (index == -1) {
            // do nothing
        } else if (index == 0) {
            librariesCustomizer.setLibraryStorageArea(LibraryStorageArea.GLOBAL);
        } else if (index > 0) {
            URL u = null;
            try {
                //#131452 prevent space in path problem when converting to URL.
                File loc = FileUtil.normalizeFile(new File((String) libraryManagerComboBox.getModel().getSelectedItem()));
                u = Utilities.toURI(loc).toURL();
            } catch (MalformedURLException ex) {
                Exceptions.printStackTrace(ex);
            }
            librariesCustomizer.setLibraryStorageArea(findLibraryStorageArea(u));
        }
    }//GEN-LAST:event_libraryManagerComboBoxActionPerformed

    @NonNull
    private LibraryStorageArea findLibraryStorageArea(@NonNull final URL u) {
        for (ArealLibraryProvider<?,?> alp : Lookup.getDefault().lookupAll(ArealLibraryProvider.class)) {
            for (LibraryStorageArea area : alp.getOpenAreas()) {
                if (u.toString().equals(area.getLocation().toString())) {
                    return area;
                }
            }
        }
        return LibraryStorageArea.GLOBAL;
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JComboBox libraryManagerComboBox;
    private javax.swing.JPanel placeholder;
    // End of variables declaration//GEN-END:variables
    
}
